package main

import (
	"strings"
)

func containsChar(s string, f func(byte) bool) bool {
	for i := 0; i < len(s); i++ {
		if f(s[i]) {
			return true
		}
	}
	return false
}

func isValidPkgName(name string) bool {
	if len(name) == 0 {
		return false
	}
	return !containsChar(name, func(b byte) bool { return b != '_' && (b < 'a' || b > 'z') })
}

func toupper(c byte) byte {
	if c >= 'a' && c <= 'z' {
		return c - 'a' + 'A'
	} else {
		return c
	}
}

func tolower(c byte) byte {
	if c >= 'A' && c <= 'Z' {
		return c - 'A' + 'a'
	} else {
		return c
	}
}

func camelCase(name string, beginLower bool) string {
	var s strings.Builder
	s.Grow(len(name))
	lower := beginLower
	for i := 0; i < len(name); i++ {
		c := name[i]
		if c == '_' {
			lower = false
			continue
		}
		if lower {
			s.WriteByte(tolower(c))
		} else {
			s.WriteByte(toupper(c))
			lower = true
		}
	}
	return s.String()
}

func removePrefix(prefixes []string, s string) string {
	for _, prefix := range prefixes {
		if strings.HasPrefix(s, prefix) {
			return s[len(prefix):]
		}
	}
	return s
}

var (
	sqlReservedKeyword = map[string]bool{
		"select":   true,
		"insert":   true,
		"update":   true,
		"delete":   true,
		"create":   true,
		"alter":    true,
		"drop":     true,
		"truncate": true,
		"replace":  true,
		"set":      true,
		"from":     true,
		"where":    true,
		"and":      true,
		"or":       true,
		"order":    true,
		"group":    true,
		"by":       true,
	}
)

func reserveSqlName(columnName string) string {
	if sqlReservedKeyword[columnName] {
		return "`" + columnName + "`"
	} else {
		return columnName
	}
}
